package com.deimos.tests;

import static org.junit.Assert.assertTrue;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.llom.util.AXIOMUtil;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
import org.vast.ows.sps.SPSUtils;
import org.vast.ows.sps.StatusReport;
import org.vast.ows.sps.StatusReport.RequestStatus;

import com.deimos.HMA;
import com.deimos.UtilsDeimos;
import com.deimos.dataBase.TaskController;
import com.spotimage.eosps.EOConstants.AcqStatus;

public class Validate {
    private static HMA hma = new HMA();
    SPSUtils utils = new SPSUtils();
    static String taskId = null;

    @BeforeClass
    public static void init() {
	TaskController taskController = new TaskController();
	taskController.createTables(true);
    }
    
    @Test
    public void ValidateFeasible() throws Exception{
	OMElement request, response;
	request = AXIOMUtil.stringToOM(AllTests.readTest(AllTests.test_dir + "Validate_Step_1_Submit_Request.xml"));
	response = hma.Submit(request);

	StatusReport report = UtilsDeimos.readParams(response.toString()).getReport();
	if (report.getDescription().contains(" is in use by the task ")) {
	    taskId = report.getDescription().split(" is in use by the task ")[1];
	    cancel_is_in_use();
	    taskId = null;
	    ValidateFeasible();
	}

	if (taskId == null) {
	    taskId = UtilsDeimos.readParams(response.toString()).getReport().getTaskID();
	    assertTrue(UtilsDeimos.readParams(response.toString()).getReport().getRequestStatus() == RequestStatus.Accepted);
	    Validate_Step_2();
	    cancel_is_in_use();
	}
    }
    
    public void Validate_Step_2() throws Exception{
	OMElement request, response;
	request = AXIOMUtil.stringToOM(AllTests.readTest(AllTests.test_dir + "Validate_Step_2_Validate_Request.xml").replace("TASKID", taskId));
	Thread.sleep(5000);
	response = hma.Validate(request);
	assertTrue(response.toString().contains(AcqStatus.VALIDATED.toString()));
    }
    
    @After
    public void cancel_is_in_use() throws Exception {
	OMElement request;
	if (taskId == null)
	    return;
	request = AXIOMUtil.stringToOM(AllTests.readTest(AllTests.test_dir + "Validate_Step_3_Cancel_Request.xml").replace("TASKID", taskId));
	hma.Cancel(request);
    }
}
